package com.bw.module_main

import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.main.adapter.MainPageAdapter
import com.bw.lib_base.path.RouterPath
import com.bw.lib_base.view.BaseActivity
import com.bw.module_main.databinding.ActivityMainBinding
import com.bw.module_main.navtab.NavTabItem
import me.majiajie.pagerbottomtabstrip.NavigationController
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener

@Route(path = RouterPath.PATH_MAIN_PAGE)
class MainActivity : BaseActivity<ActivityMainBinding>() {

    private lateinit var mNavController:NavigationController
    private var fragments = arrayListOf<Fragment>()
    private lateinit var mPageAdapter: MainPageAdapter

    //需要用户授权项
    private val needUserPermission= arrayListOf(
        android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
        android.Manifest.permission.READ_EXTERNAL_STORAGE,
        android.Manifest.permission.CAMERA,
        android.Manifest.permission.READ_PHONE_NUMBERS,
        android.Manifest.permission.ACCESS_FINE_LOCATION
    )

    //用户还未授权
    private val unGrantUserPermission= arrayListOf<String>()

    private var hasUnGranted=false

    override fun getLayoutId(): Int =R.layout.activity_main


    override fun initView() {

        mNavController= mDataBinding.mainBottomNav.custom()
            .addItem(newTabItem(R.drawable.tab_home_default, R.drawable.tab_home_checked, "首页"))
            .addItem(newTabItem(R.drawable.tab_server_default, R.drawable.tab_server_checked, "服务"))
            .addItem(newTabItem(R.drawable.tab_message_default, R.drawable.tab_message_checked, "消息"))
            .addItem(newTabItem(R.drawable.tab_notice_default, R.drawable.tab_notice_checked, "公告"))
            .addItem(newTabItem(R.drawable.tab_mine_default, R.drawable.tab_mine_checked, "我的"))
            .build()

        //设置Fragment
        fragments.add(ARouter.getInstance().build(RouterPath.PATH_FRAGMENT_HOME).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RouterPath.PATH_FRAGMENT_SERVICE).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RouterPath.PATH_FRAGMENT_MESSAGE).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RouterPath.PATH_FRAGMENT_NOTICE).navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RouterPath.PATH_FRAGMENT_MINE).navigation() as Fragment)

        //设置适配器
        mPageAdapter = MainPageAdapter(supportFragmentManager, fragments, FragmentPagerAdapter.BEHAVIOR_SET_USER_VISIBLE_HINT)
        mDataBinding.mainViewPager.adapter = mPageAdapter
        mDataBinding.mainViewPager.offscreenPageLimit = 4 //设置离开屏幕的Fragment缓存大小

        //底部导航选中监听事件
        mNavController.addTabItemSelectedListener(object : OnTabItemSelectedListener {
            override fun onSelected(index: Int, old: Int) {
                mDataBinding.mainViewPager.currentItem = index
            }

            override fun onRepeat(index: Int) {
                mDataBinding.mainViewPager.currentItem = index
            }
        })

        //设置ViewPager的切换监听事件
        mDataBinding.mainViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                Log.i("===============", "onPageScrolled: position: $position")
            }

            override fun onPageSelected(position: Int) {
                Log.i("===============", "onPageSelected: position: $position")
                mNavController.setSelect(position)
            }

            override fun onPageScrollStateChanged(state: Int) {
                Log.i("===============", "onPageScrollStateChanged: state: $state")

            }
        })

        //设置公告数字提示
        mNavController.setHasMessage(3, true)
        mNavController.setMessageNumber(3, 5)


        //延迟2秒后发起授权
        mDataBinding.mainViewPager.postDelayed({ autoRequestPermission() },2000)
    }

    private fun autoRequestPermission():Boolean{
        //判断是否是Android6.0以上版本
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){//M-->6.0

            //清理一下
            unGrantUserPermission.clear()

            //找到用户没有授权成功的项
            needUserPermission.forEach {
                var state=checkSelfPermission(it)
                if (state==PackageManager.PERMISSION_DENIED){//还没有授权
                    unGrantUserPermission.add(it)
                }
            }

            //发起授权请求
            if (unGrantUserPermission.size>0){
                requestPermissions(unGrantUserPermission.toTypedArray(),102)
                return false
            }
        }

        return true

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        //对于用户授权的结果要检验
        if (requestCode==102 && Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            unGrantUserPermission.forEach {
                if (checkSelfPermission(it)==PackageManager.PERMISSION_DENIED){
                    hasUnGranted=true
                }
            }
        }

        //如果存在 给Dialog即可
        if (hasUnGranted){
            var builder = AlertDialog.Builder(this@MainActivity)
            builder.setTitle("权限提示")
            builder.setMessage("没有授权，请到应用详情中设置")
            builder.setPositiveButton("去设置") { dialog, _ ->
                dialog.dismiss()
                hasUnGranted = false
                openAppDetailPage()
            }
            builder.setNegativeButton("取消") { dialog, _ ->
                dialog.dismiss()
                hasUnGranted = false
            }
        }
    }

    /**
     * 打开应用详情页面
     */
    private fun openAppDetailPage() {
        var intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.fromParts("package", packageName, null)
        this@MainActivity.startActivity(intent)
    }


    private fun newTabItem(defaultResId:Int,checkedResId:Int,title:String):BaseTabItem{
        var normalTabView=NavTabItem(this@MainActivity).apply {
            initData(defaultResId,checkedResId,title)
            setDefaultTextColor(R.color.main_bottom_default_color)
            setCheckedTextColor(R.color.main_bottom_check_color)
        }
        return normalTabView
    }
}